********************************************************************************
* This program generates indirect foreign energy prices
*
* Authors: Karl
* Updated: 2019 0624
*
* Edited: Aug 2020
********************************************************************************


*************************************************************************
* 				PART I . claim inputs and outputs
*************************************************************************
clear programs 

// Input data:

// intensities.
// created in 3_2_1_gen_energyintensities.do
global ENERGY_I = "$EI/energy_intensity_2007_naics2007.dta"

// intensities.
// created in 3_2_1_gen_energyintensities.do
global ENERGY_I_IO = "$IO/IO_energyintensity.dta"


// energy prices: 
// created in 3_1_2_2_gen_energyprice_2international_allindustries_regionlevel.do
global ENERGY_P = "$energy_price/importexport_energy_price_industry_year_region-level.dta"

// Output data:
global NAICS_PRICE = "$energy_price/energy_foreignprice_industry_year_indirect.dta"


// clean energy price file

* (1). use the NAICS 2007-2012 mapping from domestic price file
use "$energy_price/energy_price_industry_year.dta", clear
drop sector naics_mecs
keep if year >= 1995 & year <= 2015
replace naics = naics2007 if year <= 2012 & naics != 339111
tostring naics, gen(naics_str)

replace naics_str = "31131X" if floor(naics/10) == 31131
replace naics_str = "31181X" if floor(naics/10) == 31181
replace naics_str = "31511X" if floor(naics/10) == 31511 & year <= 2012
replace naics_str = "33631X" if floor(naics/10) == 31511 & year <= 2012

keep naics2007 naics2012 naics naics_str year

merge m:1 naics_str year using "$ENERGY_P"
keep if _merge == 3
drop _merge
keep naics2007 naics2012 naics naics_str year price_imports price_exports


//UP TO THIS POINT, we were just cleaning naics years	
tempfile prices  price_clean
drop naics2012 naics naics_str
rename naics2007 naics
quietly save `prices'
quietly save `price_clean'

rename naics naics_row
joinby naics_row using $ENERGY_I_IO

gen ind_price_imp = io_v_norm*price_imports
gen ind_price_exp = io_v_norm*price_exports


collapse (sum) ind_price_imp ind_price_exp, by(naics year)
merge 1:1 naics year using `price_clean', keepusing(price_imports price_exports) nogen keep(match)
//add in industrylabels
merge m:1 naics using "$ENERGY_I", nogen norep keepus(naics2012 industryname2007)
drop if ind_price_imp == . & ind_price_exp == .

label var ind_price_imp "indirect import price， 2010$ per mi"
label var ind_price_exp "indirect export price， 2010$ per mi"
save "$NAICS_PRICE", replace
